import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from './index'

NProgress.configure({ showSpinner: false })
const whiteList = ['Error', 'Index', 'RedbagView']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const store = useAppStore()

  if (whiteList.indexOf(to.name as string) >= 0) {
    return next()
  }

  if (!store.logined) {
    // 如果用户没有登陆，判断是否识别到用户信息，否则进入错误页面
    const user = cache.getTgUser()
    if (user) {
      try {
        store.tgUser = user
        store.user = await apis.api.loginOauth()
      } catch (error) {
        console.error('tg Error', error)
        return next('/error')
      }
    } else {
      return next('/error')
    }
  }
  next()
})

router.afterEach(() => NProgress.done())
